package com.httpUtils;

import android.util.Log;

import com.android.volley.AuthFailureError;
import com.android.volley.DefaultRetryPolicy;
import com.android.volley.NetworkResponse;
import com.android.volley.ParseError;
import com.android.volley.Request;
import com.android.volley.Response;
import com.android.volley.toolbox.HttpHeaderParser;

import org.json.JSONObject;

import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.util.List;
import java.util.Map;


/**
 * Created by gyzhong on 15/3/1.
 */
public class FileUploadRequest extends Request<String> {

    /**
     * 正确数据的时候回掉用
     */
    Response.Listener<String>   mListener ;
    /*请求 数据通过参数的形式传入*/
    private List<FileParm> fileParms;
    private Map<String ,Object> requstParms;


    private String BOUNDARY = "--------------520-13-14"; //数据分隔线
    private String MULTIPART_FORM_DATA = "multipart/form-data";

    public FileUploadRequest(String url, List<FileParm> fileParms, Map<String, Object> requstParms,  Response.Listener<String> listener, Response.ErrorListener errorListener) {
        super(Method.POST, url, errorListener);
        this.mListener = listener ;
        setShouldCache(false);
        this.fileParms = fileParms ;
        this.requstParms = requstParms;
        setRetryPolicy(new DefaultRetryPolicy(5000,DefaultRetryPolicy.DEFAULT_MAX_RETRIES,DefaultRetryPolicy.DEFAULT_BACKOFF_MULT));
    }

    /**
     * 这里开始解析数据
     * @param response Response from the network
     * @return
     */
    @Override
    protected Response<String> parseNetworkResponse(NetworkResponse response) {
        try {
            String mString =
                    new String(response.data, HttpHeaderParser.parseCharset(response.headers));
            Log.v("zgy", "====mString===" + mString);

            return Response.success(mString,
                    HttpHeaderParser.parseCacheHeaders(response));
        } catch (UnsupportedEncodingException e) {
            return Response.error(new ParseError(e));
        }
    }

    /**
     * 回调正确的数据
     * @param response The parsed response returned by
     */
    @Override
    protected void deliverResponse(String response) {
        mListener.onResponse(response);
    }

    @Override
    public byte[] getBody() throws AuthFailureError {
        if (fileParms != null&& fileParms.size()>0){
            ByteArrayOutputStream bos = new ByteArrayOutputStream() ;
            StringBuffer sb= new StringBuffer() ;
            if (requstParms !=null&& requstParms.size()>0){
                for (String key : requstParms.keySet()) {

//                    Content-Disposition: form-data; name="UserName"
//
//                    5
                      /*第一行*/
                    sb.append("--"+BOUNDARY);
                    sb.append("\r\n") ;
            /*第二行*/
                    sb.append("Content-Disposition: form-data;");
                    sb.append(" name=\"");
                    sb.append(key) ;
                    sb.append("\"") ;
                    sb.append("\r\n") ;
            /*第三行*/
                    sb.append("Content-Type: ");
                    sb.append("text/plain; charset=UTF-8") ;
                    sb.append("\r\n") ;
            /*第四行*/
                    sb.append("Content-Transfer-Encoding: ");
                    sb.append(" 8bit") ;
                    sb.append("\r\n") ;
                    sb.append("\r\n") ;
                    sb.append(requstParms.get(key).toString());
                    sb.append("\r\n") ;

                }

            }



            int N = fileParms.size() ;
            FileParm fileParm ;

            for (int i = 0; i < N ;i++){
                fileParm = fileParms.get(i) ;

            /*第一行*/
                sb.append("--"+BOUNDARY);
                sb.append("\r\n") ;
            /*第二行*/
                sb.append("Content-Disposition: form-data;");
                sb.append(" name=\"");
                sb.append(fileParm.getName()) ;
                sb.append("\"") ;
                sb.append("; filename=\"") ;
                sb.append(fileParm.getFile().getName()) ;
                sb.append("\"");
                sb.append("\r\n") ;
            /*第三行*/
                sb.append("Content-Type: ");
                sb.append(fileParm.getMime()) ;
                sb.append("\r\n") ;
            /*第四行*/
                sb.append("Content-Transfer-Encoding: ");
                sb.append(" binary") ;
                sb.append("\r\n") ;

                try {
                    bos.write(sb.toString().getBytes("utf-8"));
                /*第五行*/
                    bos.write(fileParm.getValue());
                    bos.write("\r\n".getBytes("utf-8"));
                } catch (IOException e) {
                    e.printStackTrace();
                }

            }
        /*结尾行*/
            String endLine = "--" + BOUNDARY + "--" + "\r\n" ;
            try {
                bos.write(endLine.toString().getBytes("utf-8"));
            } catch (IOException e) {
                e.printStackTrace();
            }
            Log.v("zgy","=====formImage====\n"+bos.toString()) ;
            return bos.toByteArray();
        }else {
            return super.getBody() ;
        }

    }

    @Override
    public String getBodyContentType() {
        return MULTIPART_FORM_DATA+"; boundary="+BOUNDARY;
    }
}
